﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using MyServer.Common;
using MyServer.Udp;

namespace ClientUI
{
    public partial class Udp : Form
    {
        public Udp()
        {
            InitializeComponent();
        }

        public static UdpCenter Center;
        UdpClient Client;

        private void button1_Click(object sender, EventArgs e)
        {
            IPAddress ipaddr = IPAddress.Parse(textBox2.Text);
            IPEndPoint localEndP = new IPEndPoint(ipaddr, (int)numericUpDown2.Value);
            Center = new UdpCenter();
            Center.Start();
            Client = new UdpClient(localEndP);
            Center.Reader.AfterOperateData += Reader_AfterOperateData;
        }

        private delegate void reader_a_d(object sender,DataAfterOperateEventArgs e);
        void Reader_AfterOperateData(object sender, DataAfterOperateEventArgs e)
        {
            if (treeView1.InvokeRequired)
            {
                reader_a_d de = new reader_a_d(Reader_AfterOperateData);
                treeView1.Invoke(de, sender, e);
            }
            else
            {
                DataPackageCollection pkg = e.OperateData;
                if (pkg.State == PackageCollectionState.ReciveCompelete)
                {
                    string s = Encoding.UTF8.GetString(DataPacker.UnPackData(pkg));
                    TreeNode tnode = new TreeNode();
                    tnode.Text = ((UdpPkgInfo)pkg.Tag).BindPoint.ToString();
                    tnode.Tag = s;
                    treeView1.Nodes.Add(tnode);
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.numericUpDown1.Maximum = IPEndPoint.MaxPort;
            this.numericUpDown2.Maximum = IPEndPoint.MaxPort;
            this.numericUpDown1.Minimum = IPEndPoint.MinPort;
            this.numericUpDown2.Minimum = IPEndPoint.MinPort;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            IPAddress ipaddr = IPAddress.Parse(textBox1.Text);
            IPEndPoint serverEndp = new IPEndPoint(IPAddress.Broadcast, (int)numericUpDown1.Value);
            Center.SendTo(Client, serverEndp, Encoding.UTF8.GetBytes(textBox3.Text), "pkg", true);
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                this.textBox4.Text = (String)treeView1.SelectedNode.Tag;
            }
        }
    }
}
